<?php 

function handleOboxRequest($dataQuery) {
	// Build the SQLXML query
	$q1 = sprintf($dataQuery["queryTemplate"], utf8_decode($dataQuery["query"]));
	$query = sprintf("SELECT (%s FOR XML RAW, ROOT('Results')) AS Results", $q1);	
	
	// Fetch the query results from DB
	$db = new DB($dataQuery["server"], $dataQuery["dbname"]);
	$data = $db->query($query, true);
	
	// Apply a XSLT transformation to build the output the onebox module from the XML data
	$result = applyXSLT($data, $dataQuery["format"], array("query" => $dataQuery["query"]));
	
	// Output the result
	header('Content-type: text/xml');
	echo $result;
}

// Applies a XSLT transformation to a XML file
function applyXSLT($xml, $xsltPath, $params = array()) {
	if($xml == "") return "";
	
	$xml = utf8_encode($xml);

	$xp = new XsltProcessor();

	$xsl = new DomDocument;
	$xsl->load($xsltPath);
    
	$xp->setParameter('', $params);
	
	$xp->importStylesheet($xsl);
	
	$xml_doc = new DomDocument;
	$xml_doc->loadXML($xml);
  
	if ($output = $xp->transformToXML($xml_doc)) {
      return $output;
	} else {
      trigger_error('XSL transformation failed.', E_USER_ERROR);
	} 
}

class DB {
	public $conn;
	
	// Opens a DB connection
	function __construct($dbServer, $dbName) {
       $this->conn = sqlsrv_connect($dbServer, array("Database" => $dbName));
	   
	   if($this->conn === false ) { trigger_error( print_r( sqlsrv_errors(), true), E_USER_ERROR); }
	}
	
	// Executes sql query and optionally closes the connection
	public function query($query, $close = false) {
		$stmt = sqlsrv_query($this->conn, $query);
	
		if($stmt === false) { trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR); }
		
		$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
		
		sqlsrv_free_stmt($stmt);
		
		if($close) { $this->close(); }
		
		return $row[0];
	}
	
	// Closes the DB connection 
	public function close() {
		sqlsrv_close($this->conn);
	}	
}